#include "PlatformJumpScene.h"
#include "GameOverScene.h"
#include "../Renderer/TextureRenderer.h"
#include <graphics.h>
#include <iostream>
#include <tchar.h>
#include <algorithm>
#include <iomanip>  // For std::fixed and std::setprecision

// PlayerController implementation
PlayerController::PlayerController(GameObject* gameObject, InputHandler* inputHandler)
    : Component(gameObject), inputHandler_(inputHandler), moveSpeed_(200.0f), jumpForce_(-500.0f) {
    rigidbody_ = gameObject->getComponent<Rigidbody>();
}

void PlayerController::update(float deltaTime) {
    if (!enabled_ || !rigidbody_) return;

    float horizontalInput = 0.0f;

    // Use direct GetAsyncKeyState for reliable input detection
    // Horizontal movement
    if ((GetAsyncKeyState(VK_LEFT) & 0x8000) || (GetAsyncKeyState('A') & 0x8000)) {
        horizontalInput = -1.0f;
        Renderer::setDirection(0);
    }
    if ((GetAsyncKeyState(VK_RIGHT) & 0x8000) || (GetAsyncKeyState('D') & 0x8000)) {
        horizontalInput = 1.0f;
        Renderer::setDirection(1);
    }
    // Set horizontal velocity
    rigidbody_->setVelocity(horizontalInput * moveSpeed_, rigidbody_->getVelocityY());

    // Jump - improved input detection with multiple methods
    bool isGrounded = rigidbody_->isGrounded();
    bool jumpPressed = false;

    // Method 1: Check for current key press (for held keys)
    bool spaceCurrentlyPressed = (GetAsyncKeyState(VK_SPACE) & 0x8000) != 0;
    bool wCurrentlyPressed = (GetAsyncKeyState('W') & 0x8000) != 0;

    // Method 2: Check for "just pressed" state with improved tracking
    static bool prevSpaceState = false;
    static bool prevWState = false;
    static float jumpBuffer = 0.0f; // Jump buffer timer
    static float groundedBuffer = 0.0f; // Grounded buffer timer

    const float bufferTime = 0.1f; // 100ms buffer

    bool spaceJustPressed = spaceCurrentlyPressed && !prevSpaceState;
    bool wJustPressed = wCurrentlyPressed && !prevWState;    // Update jump buffer - if jump was pressed recently, keep it active
    if (spaceJustPressed || wJustPressed) {
        jumpBuffer = bufferTime;
        // std::cout << "Jump input detected! Buffer set." << std::endl; // Commented out to reduce console spam
    }

    // Update grounded buffer - if player was grounded recently, keep it active
    if (isGrounded) {
        groundedBuffer = bufferTime;
    }

    // Decrease buffers
    if (jumpBuffer > 0) jumpBuffer -= deltaTime;
    if (groundedBuffer > 0) groundedBuffer -= deltaTime;

    // Jump logic: either just pressed jump, or jump is in buffer, and either grounded or recently grounded
    bool canJump = (jumpBuffer > 0) && (isGrounded || groundedBuffer > 0);    if (canJump) {
        rigidbody_->setVelocity(rigidbody_->getVelocityX(), jumpForce_);
        jumpBuffer = 0; // Clear jump buffer after successful jump
        groundedBuffer = 0; // Clear grounded buffer after jump
        // Debug: Only log jump when it actually happens
        std::cout << "[Player] Jump executed!" << std::endl;
    }    // Update previous states
    prevSpaceState = spaceCurrentlyPressed;
    prevWState = wCurrentlyPressed;

    // Debug output - only for significant state changes or major events
    static int debugCounter = 0;
    static bool wasGrounded = false;
    static int stableGroundedFrames = 0;
    static int stableAirborneFrames = 0;
    debugCounter++;

    // Track stable states to avoid spam from micro-state changes
    if (isGrounded) {
        stableGroundedFrames++;
        stableAirborneFrames = 0;
    }
    else {
        stableAirborneFrames++;
        stableGroundedFrames = 0;
    }

    // Only output debug info for stable state changes (avoid micro-bouncing)
    bool stableStateChange = false;
    if (!wasGrounded && isGrounded && stableGroundedFrames >= 3) {
        // Just became stably grounded
        std::cout << "[Player] Landed (VelY: " << std::fixed << std::setprecision(1)
            << rigidbody_->getVelocityY() << ")" << std::endl;
        stableStateChange = true;
    }
    else if (wasGrounded && !isGrounded && stableAirborneFrames >= 3) {
        // Just became stably airborne
        std::cout << "[Player] Airborne (VelY: " << std::fixed << std::setprecision(1)
            << rigidbody_->getVelocityY() << ")" << std::endl;
        stableStateChange = true;
    }

    // Periodic debug output (every 10 seconds) for general state monitoring
    if (debugCounter % 600 == 0) {
        std::cout << "[Player] Status - Grounded: " << isGrounded
            << ", VelY: " << std::fixed << std::setprecision(1) << rigidbody_->getVelocityY() << std::endl;
    }

    // Update wasGrounded only after stable state changes
    if (stableStateChange) {
        wasGrounded = isGrounded;
    }
}

// PlatformJumpScene implementation
PlatformJumpScene::PlatformJumpScene(const std::string& name)
    : Scene(name), player_(nullptr), score_(0), gameTime_(0.0f), gameTimeLimit_(30.0f), gameEnded_(false) {
    gameWorld_ = std::make_unique<GameWorld>();
    inputHandler_ = std::make_unique<InputHandler>();
    camera_ = std::make_unique<Camera>(800.0f, 600.0f);
    backgroundRenderer_ = std::make_unique<BackgroundRenderer>();
}

// Static constants for world bounds
const float PlatformJumpScene::WORLD_WIDTH = 2000.0f;
const float PlatformJumpScene::WORLD_HEIGHT = 800.0f;

PlatformJumpScene::~PlatformJumpScene() = default;

void PlatformJumpScene::OnCreate() {
    std::cout << "[Scene] Creating platform jump game scene" << std::endl;

    // Reset game state
    score_ = 0;
    gameTime_ = 0.0f;
    gameEnded_ = false;

    // Load textures for platforms and ground
    loadTextures();

    // Load game background music
    auto& audioMgr = GameEngine::GameAudioManager::getInstance();
    bool audioLoaded = audioMgr.loadAudio("platform_bgm", "lumv2/Game_engine_demo_v1/assets/audio/platform_background.mp3");
    if (audioLoaded) {
        std::cout << "[Audio] Background music loaded successfully" << std::endl;
    }
    else {
        std::cout << "[Audio] Failed to load background music" << std::endl;
    }

    setupCamera();
    setupBackground();
    createPlayer();
    createPlatforms();

    // Initialize platform scoring array
    platformScored_.resize(platforms_.size(), false);
    std::cout << "[Scene] Platform jump scene created with " << platforms_.size() << " platforms" << std::endl;
}

void PlatformJumpScene::OnDestroy() {
    std::cout << "[Scene] Destroying platform jump game scene" << std::endl;

    // Stop and unload background music
    auto& audioMgr = GameEngine::GameAudioManager::getInstance();
    audioMgr.stopBackgroundMusic();
    audioMgr.unloadAudio("platform_bgm");

    // Unload textures
    auto* assetManager = AssetManager::GetInstance();
    if (assetManager->HasAsset("ground_texture")) {
        assetManager->UnloadAsset("ground_texture");
    }
    if (assetManager->HasAsset("platform_texture")) {
        assetManager->UnloadAsset("platform_texture");
    }

    gameWorld_->clear();
}

void PlatformJumpScene::OnActivate() {
    std::cout << "[Scene] Activating platform jump game scene" << std::endl;

    // Reset game state when scene is activated (for restart functionality)
    resetGame();

    // Start playing background music
    auto& audioMgr = GameEngine::GameAudioManager::getInstance();
    bool musicStarted = audioMgr.playBackgroundMusic("platform_bgm", true); // Loop the background music
    if (musicStarted) {
        std::cout << "[Audio] Background music started" << std::endl;
    }
}

void PlatformJumpScene::OnDeactivate() {
    std::cout << "[Scene] Deactivating platform jump game scene" << std::endl;

    // Stop background music when scene is deactivated
    auto& audioMgr = GameEngine::GameAudioManager::getInstance();
    audioMgr.stopBackgroundMusic();
}

void PlatformJumpScene::Update(float deltaTime) {
    if (gameEnded_) return;

    inputHandler_->update();

    // Update game objects (this includes physics)
    gameWorld_->update(deltaTime);

    // Check collisions after physics update to correct positions
    checkCollisions();

    // Update camera
    camera_->update(deltaTime);

    // Update game state
    updateGameState(deltaTime);

    // Check platform scoring
    checkPlatformScoring();
}

void PlatformJumpScene::Render() {
    // Clear screen
    cleardevice();

    // Render background with camera offset for parallax effect
    if (backgroundRenderer_) {
        Vector2 cameraOffset(camera_->getX(), camera_->getY());
        backgroundRenderer_->Render(cameraOffset);
    }

    // Render game world with camera
    gameWorld_->render(camera_.get());

    // Render UI
    renderUI();
}

void PlatformJumpScene::createPlayer() {
    player_ = gameWorld_->createGameObject("Player");

    // Set player position and size
    player_->getTransform()->setPosition(100, 400);
    player_->getTransform()->setSize(40, 50);

    // Add renderer
    auto renderer = player_->addComponent<Renderer>();
    renderer->setColor(BLACK);

    // Add rigidbody
    auto rigidbody = player_->addComponent<Rigidbody>();
    rigidbody->setUseGravity(true);

    // Add player controller
    auto controller = player_->addComponent<PlayerController>(inputHandler_.get());

    // Set collision box
    auto collisionBox = std::make_shared<RectangleCollisionBox>(
        player_->getTransform()->getX(),
        player_->getTransform()->getY(),
        player_->getTransform()->getWidth(),
        player_->getTransform()->getHeight()
    );
    player_->setCollisionBox(collisionBox);

    // Set camera target to player
    camera_->setTarget(player_);
}

void PlatformJumpScene::createPlatforms() {
    auto* assetManager = AssetManager::GetInstance();

    // Create ground platform (extended for larger world)
    auto ground = gameWorld_->createGameObject("Ground");
    ground->getTransform()->setPosition(0, 550);
    ground->getTransform()->setSize(WORLD_WIDTH, 30);

    // Try to use texture renderer for ground
    auto groundTextureRenderer = ground->addComponent<TextureRenderer>();
    if (assetManager->HasAsset("ground_texture")) {
        groundTextureRenderer->SetTexture("ground_texture");
        groundTextureRenderer->SetRenderMode(TextureRenderer::RenderMode::Tile);
        groundTextureRenderer->SetTextureScale(1.0f, 1.0f);
        std::cout << "[Platform] Ground using texture rendering" << std::endl;
    }
    else {
        // Fallback to color rendering
        ground->removeComponent<TextureRenderer>();
        auto groundRenderer = ground->addComponent<Renderer>();
        groundRenderer->setColor(RGB(139, 69, 19)); // Brown color for ground
        std::cout << "[Platform] Ground using color fallback" << std::endl;
    }

    auto groundCollision = std::make_shared<RectangleCollisionBox>(0, 550, WORLD_WIDTH, 30);
    ground->setCollisionBox(groundCollision);
    platforms_.push_back(ground);

    // Create more jumping platforms spread across the world
    struct PlatformData {
        float x, y, width, height;
    };

    std::vector<PlatformData> platformsData = {
        // Near start area
        {200, 450, 100, 20},
        {350, 350, 100, 20},
        {150, 250, 100, 20},
        {400, 200, 100, 20},
        {250, 150, 100, 20},
        {500, 400, 80, 20},
        {600, 300, 80, 20},
        {700, 200, 80, 20},

        // Middle area
        {900, 450, 120, 20},
        {1100, 350, 100, 20},
        {1050, 250, 80, 20},
        {1250, 200, 100, 20},
        {1150, 150, 90, 20},
        {1400, 400, 100, 20},
        {1500, 300, 80, 20},

        // Far area
        {1700, 450, 100, 20},
        {1600, 350, 80, 20},
        {1750, 250, 120, 20},
        {1650, 150, 100, 20},
        {1850, 400, 80, 20}
    };

    for (size_t i = 0; i < platformsData.size(); ++i) {
        const auto& data = platformsData[i];

        auto platform = gameWorld_->createGameObject("Platform" + std::to_string(i));
        platform->getTransform()->setPosition(data.x, data.y);
        platform->getTransform()->setSize(data.width, data.height);

        // Try to use texture renderer for platforms
        auto platformTextureRenderer = platform->addComponent<TextureRenderer>();
        if (assetManager->HasAsset("platform_texture")) {
            platformTextureRenderer->SetTexture("platform_texture");
            platformTextureRenderer->SetRenderMode(TextureRenderer::RenderMode::Tile);
            platformTextureRenderer->SetTextureScale(0.5f, 1.0f); // Scale texture for better tiling
        }
        else {
            // Fallback to color rendering
            platform->removeComponent<TextureRenderer>();
            auto renderer = platform->addComponent<Renderer>();
            renderer->setColor(RGB(160, 82, 45)); // Saddle brown color for platforms
        }

        auto collision = std::make_shared<RectangleCollisionBox>(data.x, data.y, data.width, data.height);
        platform->setCollisionBox(collision);
        platforms_.push_back(platform);
    }

    std::cout << "[Platform] Created " << platforms_.size() << " platforms with texture support" << std::endl;
}

void PlatformJumpScene::checkCollisions() {
    if (!player_) return;

    auto collisions = gameWorld_->checkCollisions(player_);
    auto playerRigidbody = player_->getComponent<Rigidbody>();

    if (!playerRigidbody) return;

    bool onPlatform = false;
    Transform* playerTransform = player_->getTransform();

    for (auto* platform : collisions) {
        // Check if it's a platform
        bool isPlatform = false;
        for (auto* p : platforms_) {
            if (p == platform) {
                isPlatform = true;
                break;
            }
        }

        if (isPlatform) {
            Transform* platformTransform = platform->getTransform();

            // Get current positions and bounds
            float playerLeft = playerTransform->getX();
            float playerRight = playerLeft + playerTransform->getWidth();
            float playerTop = playerTransform->getY();
            float playerBottom = playerTop + playerTransform->getHeight();

            float platformLeft = platformTransform->getX();
            float platformRight = platformLeft + platformTransform->getWidth();
            float platformTop = platformTransform->getY();
            float platformBottom = platformTop + platformTransform->getHeight();

            // Calculate overlap amounts for each direction
            float overlapLeft = playerRight - platformLeft;   // Player hitting platform from left
            float overlapRight = platformRight - playerLeft;  // Player hitting platform from right
            float overlapTop = playerBottom - platformTop;    // Player hitting platform from above
            float overlapBottom = platformBottom - playerTop; // Player hitting platform from below

            // Find the smallest overlap (minimum separation)
            float minOverlap =
                (std::min)( // 注意：min 和括号之间无空格
                    (std::min)(overlapLeft, overlapRight),
                    (std::min)(overlapTop, overlapBottom)
                    );

            // Apply collision response based on the direction of smallest overlap
            const float tolerance = 8.0f; // Increased tolerance for better collision detection

            if (minOverlap == overlapTop && minOverlap > 0 && minOverlap < tolerance + 25) {
                // Collision from above (landing on platform)
                if (playerRigidbody->getVelocityY() >= 0) {
                    // Use more precise positioning to prevent sinking
                    float correctedY = platformTop - playerTransform->getHeight();
                    playerTransform->setPosition(playerTransform->getX(), correctedY);
                    playerRigidbody->setVelocity(playerRigidbody->getVelocityX(), 0);
                    playerRigidbody->setGrounded(true);                    onPlatform = true;

                    // Debug output for landing - only when significant landing occurs
                    static float lastLandingY = -1000.0f;
                    if (abs(correctedY - lastLandingY) > 50.0f) { // Only log if landing is far from last landing
                        std::cout << "[Collision] Player landed on platform at Y: " << correctedY << std::endl;
                        lastLandingY = correctedY;
                    }
                }
            }
            else if (minOverlap == overlapBottom && minOverlap > 0 && minOverlap < tolerance + 25) {
                // Collision from below (hitting platform with head)
                if (playerRigidbody->getVelocityY() < 0) {
                    float correctedY = platformBottom;
                    playerTransform->setPosition(playerTransform->getX(), correctedY);
                    playerRigidbody->setVelocity(playerRigidbody->getVelocityX(), 0);
                }
            }
            else if (minOverlap == overlapLeft && minOverlap > 0 && minOverlap < tolerance + 25) {
                // Collision from left (player moving right into platform)
                if (playerRigidbody->getVelocityX() > 0) {
                    float correctedX = platformLeft - playerTransform->getWidth();
                    playerTransform->setPosition(correctedX, playerTransform->getY());
                    playerRigidbody->setVelocity(0, playerRigidbody->getVelocityY());
                }
            }
            else if (minOverlap == overlapRight && minOverlap > 0 && minOverlap < tolerance + 25) {
                // Collision from right (player moving left into platform)
                if (playerRigidbody->getVelocityX() < 0) {
                    float correctedX = platformRight;
                    playerTransform->setPosition(correctedX, playerTransform->getY());
                    playerRigidbody->setVelocity(0, playerRigidbody->getVelocityY());
                }
            }

            // If we handled a collision, we can break early
            if (minOverlap > 0 && minOverlap < tolerance + 25) {
                break;
            }
        }
    }

    // If not on any platform, player is not grounded
    if (!onPlatform) {
        playerRigidbody->setGrounded(false);
    }

    // Additional safety check: if player is falling too fast and might have passed through
    // a platform, do a more thorough sweep test
    if (!onPlatform && playerRigidbody->getVelocityY() > 300.0f) {
        performContinuousCollisionCheck();
    }
}

void PlatformJumpScene::setupCamera() {
    // Set up camera properties
    camera_->setWorldBounds(0, 0, WORLD_WIDTH, WORLD_HEIGHT);
    camera_->setFollowMode(CameraFollowMode::Smooth);
    camera_->setSmoothness(3.0f);  // Moderate smoothness

    // Set dead zone for more natural camera movement
    camera_->setDeadZone(160, 120);  // 20% of screen size
    camera_->setDeadZoneEnabled(true);

    // Add slight offset to keep player not exactly centered
    camera_->setTargetOffset(0, -50);  // Show more ground below player

    // Set camera to GameWorld
    gameWorld_->setCamera(camera_.get());
}

void PlatformJumpScene::performContinuousCollisionCheck() {
    if (!player_) return;

    auto playerRigidbody = player_->getComponent<Rigidbody>();
    if (!playerRigidbody) return;

    Transform* playerTransform = player_->getTransform();
    if (!playerTransform) return;

    // Current player bounds
    float playerLeft = playerTransform->getX();
    float playerRight = playerLeft + playerTransform->getWidth();
    float playerTop = playerTransform->getY();
    float playerBottom = playerTop + playerTransform->getHeight();

    // Previous player bounds
    float prevPlayerLeft = playerRigidbody->getPreviousX();
    float prevPlayerRight = prevPlayerLeft + playerTransform->getWidth();
    float prevPlayerTop = playerRigidbody->getPreviousY();
    float prevPlayerBottom = prevPlayerTop + playerTransform->getHeight();

    // Check against all platforms using swept collision detection
    for (auto* platform : platforms_) {
        Transform* platformTransform = platform->getTransform();
        if (!platformTransform) continue;

        float platformLeft = platformTransform->getX();
        float platformRight = platformLeft + platformTransform->getWidth();
        float platformTop = platformTransform->getY();
        float platformBottom = platformTop + platformTransform->getHeight();

        // Check if player's horizontal movement path intersects with platform
        bool horizontalPathIntersects = (
            (std::max)((std::min)(playerLeft, prevPlayerLeft), platformLeft) <
            (std::min)((std::max)(playerRight, prevPlayerRight), platformRight)
            );

        // Check if player crossed the platform from above
        if (horizontalPathIntersects && playerRigidbody->getVelocityY() > 0) {
            // Player was above platform in previous frame
            bool wasAbove = prevPlayerBottom <= platformTop + 5.0f; // Small tolerance
            // Player is now below or intersecting platform
            bool isNowBelow = playerTop < platformTop;

            if (wasAbove && isNowBelow) {
                // Calculate intersection time using swept AABB
                float relativeVelocityY = playerRigidbody->getVelocityY();
                if (relativeVelocityY > 0) {
                    // Calculate the time when player's bottom edge hits platform's top edge
                    float timeToCollision = (platformTop - prevPlayerBottom) / relativeVelocityY;

                    // Check if collision happens within this frame (0 <= t <= deltaTime)
                    const float frameTime = 1.0f / 60.0f; // Assume 60 FPS
                    if (timeToCollision >= 0 && timeToCollision <= frameTime) {
                        // Collision detected! Place player on top of platform
                        float correctedY = platformTop - playerTransform->getHeight();
                        playerTransform->setPosition(playerTransform->getX(), correctedY);                        playerRigidbody->setVelocity(playerRigidbody->getVelocityX(), 0);
                        playerRigidbody->setGrounded(true);

                        // CCD debug - only log when it actually prevents tunneling
                        std::cout << "[CCD] Tunnel prevention activated at Y: " << correctedY << std::endl;
                        return; // Exit after first collision
                    }
                }
            }
        }
    }
}

void PlatformJumpScene::updateGameState(float deltaTime) {
    gameTime_ += deltaTime;

    // Check if game time limit reached
    if (gameTime_ >= gameTimeLimit_) {
        endGame(true); // Player won by surviving
    }
}

void PlatformJumpScene::checkPlatformScoring() {
    if (!player_ || gameEnded_) return;

    auto playerRigidbody = player_->getComponent<Rigidbody>();
    if (!playerRigidbody || !playerRigidbody->isGrounded()) return;

    Transform* playerTransform = player_->getTransform();
    float playerCenterX = playerTransform->getX() + playerTransform->getWidth() / 2;
    float playerBottom = playerTransform->getY() + playerTransform->getHeight();

    // Check which platform the player is standing on
    for (size_t i = 1; i < platforms_.size(); ++i) { // Skip ground platform (index 0)
        if (platformScored_[i]) continue; // Already scored this platform

        GameObject* platform = platforms_[i];
        Transform* platformTransform = platform->getTransform();

        float platformLeft = platformTransform->getX();
        float platformRight = platformLeft + platformTransform->getWidth();
        float platformTop = platformTransform->getY();

        // Check if player is standing on this platform
        if (playerCenterX >= platformLeft && playerCenterX <= platformRight &&
            abs(playerBottom - platformTop) < 5.0f) {            // Player is on this platform and hasn't scored it yet
            platformScored_[i] = true;
            score_++;
            std::cout << "[Score] Platform scored! Total: " << score_ << std::endl;
            break;
        }
    }
}

void PlatformJumpScene::renderUI() {
    // Set UI text properties
    setcolor(BLACK);
    settextcolor(BLACK);
    setbkmode(TRANSPARENT);
    settextstyle(24, 0, _T("Arial"));

    // Draw game UI
    TCHAR scoreText[50];
    _stprintf_s(scoreText, _T("Score: %d"), score_);
    outtextxy(10, 10, scoreText);

    float timeRemaining = gameTimeLimit_ - gameTime_;
    if (timeRemaining < 0) timeRemaining = 0;

    TCHAR timeText[50];
    _stprintf_s(timeText, _T("Time: %.1fs"), timeRemaining);
    outtextxy(10, 40, timeText);

    // Draw instructions
    settextstyle(16, 0, _T("Arial"));
    outtextxy(10, 80, _T("A/D or Arrows: Move"));
    outtextxy(10, 100, _T("W/Space: Jump"));
    outtextxy(10, 120, _T("Jump on platforms to score!"));

    // Time warning
    if (timeRemaining <= 5.0f && timeRemaining > 0) {
        settextcolor(RED);
        settextstyle(20, 0, _T("Arial"));
        outtextxy(10, 150, _T("TIME RUNNING OUT!"));
    }
}

void PlatformJumpScene::endGame(bool won) {
    if (gameEnded_) return;

    gameEnded_ = true;
    std::cout << "[Game] Game ended! " << (won ? "WON" : "LOST") << " | Score: " << score_
        << " | Time: " << std::fixed << std::setprecision(1) << gameTime_ << "s" << std::endl;

    // Fade out background music when game ends
    auto& audioMgr = GameEngine::GameAudioManager::getInstance();
    audioMgr.fadeOutBackgroundMusic(1.0f); // Fade out over 1 second

    // Switch to game over scene
    if (m_sceneManager) {
        // Need to get the GameOverScene and set its data
        auto gameOverScene = std::dynamic_pointer_cast<GameOverScene>(m_sceneManager->GetScene("GameOver"));
        if (gameOverScene) {
            gameOverScene->setScore(score_);
            gameOverScene->setGameWon(won);
            gameOverScene->setTimeElapsed(gameTime_);
        }
        m_sceneManager->SwitchToScene("GameOver");
    }
}

void PlatformJumpScene::resetGame() {
    std::cout << "[Game] Resetting game state" << std::endl;

    // Reset game variables
    score_ = 0;
    gameTime_ = 0.0f;
    gameEnded_ = false;

    // Reset platform scoring
    if (platformScored_.size() == platforms_.size()) {
        std::fill(platformScored_.begin(), platformScored_.end(), false);
    }
    else {
        platformScored_.assign(platforms_.size(), false);
    }

    // Reset player position and state
    if (player_) {
        player_->getTransform()->setPosition(100, 400);
        auto rigidbody = player_->getComponent<Rigidbody>();
        if (rigidbody) {
            rigidbody->setVelocity(0, 0);
            rigidbody->setGrounded(false);
        }
    }

    // Reset camera to follow player
    if (camera_ && player_) {
        camera_->setTarget(player_);
        camera_->setPosition(player_->getTransform()->getX(), player_->getTransform()->getY());
    }

    std::cout << "[Game] Reset complete" << std::endl;
}

void PlatformJumpScene::setupBackground() {
    if (!backgroundRenderer_) {
        std::cout << "[Background] Background renderer not initialized" << std::endl;
        return;
    }

    backgroundRenderer_->SetWorldBounds(WORLD_WIDTH, WORLD_HEIGHT);


    bool backgroundLoaded = false;

    std::wstring backgroundPath = L"lumv2/Game_engine_demo_v1/assets/backgrounds/sky_background.png";
    backgroundLoaded = backgroundRenderer_->SetBackground("sky_background", backgroundPath);

    if (backgroundLoaded) {
        backgroundRenderer_->SetAutoFitWorld(true);

        backgroundRenderer_->SetParallaxFactor(0.3f, 0.2f);

        std::cout << "[Background] Background loaded and configured with auto-fit mode" << std::endl;
    }
    else {
        std::cout << "[Background] Failed to load background image. Using default rendering." << std::endl;

        backgroundRenderer_->SetRenderMode(BackgroundRenderer::RenderMode::Stretch);
        backgroundRenderer_->SetParallaxFactor(0.5f, 0.3f);
    }
}

void PlatformJumpScene::loadTextures() {
    std::cout << "[Textures] Loading platform and ground textures..." << std::endl;

    auto* assetManager = AssetManager::GetInstance();

    // 加载地面纹理 - 尝试PNG和BMP格式
    bool groundLoaded = false;
    auto groundTexture = assetManager->CreateAsset<TextureAsset>("ground_texture", L"lumv2/Game_engine_demo_v1/assets/textures/ground.png");
    if (groundTexture && assetManager->LoadAsset("ground_texture")) {
        std::cout << "[Textures] Ground texture loaded successfully (PNG)" << std::endl;
        groundLoaded = true;
    }
    else {
        // 尝试BMP格式
        auto groundTextureBMP = assetManager->CreateAsset<TextureAsset>("ground_texture", L"lumv2/Game_engine_demo_v1/assets/textures/ground.bmp");
        if (groundTextureBMP && assetManager->LoadAsset("ground_texture")) {
            std::cout << "[Textures] Ground texture loaded successfully (BMP)" << std::endl;
            groundLoaded = true;
        }
    }

    if (!groundLoaded) {
        std::cout << "[Textures] Warning: Ground texture not found (tried PNG and BMP), will use fallback rendering" << std::endl;
    }

    // 加载平台纹理 - 尝试PNG和BMP格式
    bool platformLoaded = false;
    auto platformTexture = assetManager->CreateAsset<TextureAsset>("platform_texture", L"lumv2/Game_engine_demo_v1/assets/textures/platform.png");
    if (platformTexture && assetManager->LoadAsset("platform_texture")) {
        std::cout << "[Textures] Platform texture loaded successfully (PNG)" << std::endl;
        platformLoaded = true;
    }
    else {
        // 尝试BMP格式
        auto platformTextureBMP = assetManager->CreateAsset<TextureAsset>("platform_texture", L"lumv2/Game_engine_demo_v1/assets/textures/platform.bmp");
        if (platformTextureBMP && assetManager->LoadAsset("platform_texture")) {
            std::cout << "[Textures] Platform texture loaded successfully (BMP)" << std::endl;
            platformLoaded = true;
        }
    }

    if (!platformLoaded) {
        std::cout << "[Textures] Warning: Platform texture not found (tried PNG and BMP), will use fallback rendering" << std::endl;
    }

    // 设置TextureRenderer的静态摄像机
    TextureRenderer::SetRenderingCamera(camera_.get());

    std::cout << "[Textures] Texture loading complete" << std::endl;
}
